<?php

class Ads_PropertyController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }

    public function indexAction() {
        // action body
    }

    public function searchresultAction() {
        $userValidation = new Validations_User();
        $userDb = new Users_Model_Users();
        $request = $this->getRequest();
        $source = $request->getParam('source');
        $form = new Ads_Form_Search();
        $this->view->showResetButton = false;
        if ($source == 'map') {
            $stateId = $request->getParam('id');            
            $this->view->stateId = $stateId;
            $this->view->stateIds = 0;
            $stateDb = new Ads_Model_State();
            $stateData = $stateDb->getStateById($stateId);            
            $this->view->stateName = $stateData[0]['name'];
            $form->state->setValue($stateId);
            $search0 = new Validations_Search();
            $res = $search0->mapSearch($stateId);
            $this->view->searchResult = $res;
        } else if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {                                
                $values = $form->getValues();                
                $search = new Validations_Search();
                $searchResult = $search->doSearch($values);
                if ($userValidation->hasidentity()) {
                    $userId = $userValidation->getUserId();
                    $userDb->updateUser(array(
                        'last_search' => json_encode($values)
                            ), $userId);
                    $this->view->showResetButton = true;
                }
                $this->view->stateId = 0;
                $this->view->stateIds = $values['state'];
                $this->view->searchResult = $searchResult;                
            }
        } else {
            if ($userValidation->validateUser("user") && $userValidation->hasidentity()) {
                $userId = $userValidation->getUserId();
                $lastSearchByUserId = json_decode($userDb->getLastSearchByUserId($userId));
                if ($lastSearchByUserId != null) {
                    $details = array();
                    $details['state'] = $lastSearchByUserId->state;
                    $details['zipcode'] = $lastSearchByUserId->zipcode;
                    $details['propertyType'] = $lastSearchByUserId->propertyType;
                    $details['rentalPeriod'] = $lastSearchByUserId->rentalPeriod;
                    $details['furnishType'] = $lastSearchByUserId->furnishType;
                    $details['rooms'] = $lastSearchByUserId->rooms;
                    $details['size1'] = $lastSearchByUserId->size1;
                    $details['size2'] = $lastSearchByUserId->size2;
                    $details['rent1'] = $lastSearchByUserId->rent1;
                    $details['rent2'] = $lastSearchByUserId->rent2;
                    $form->state->setValue($details['state']);
                    $form->zipcode->setValue($details['zipcode']);
                    $form->propertyType->setValue($details['propertyType']);
                    $form->rentalPeriod->setValue($details['rentalPeriod']);
                    $form->furnishType->setValue($details['furnishType']);
                    $form->rooms->setValue($details['rooms']);
                    $form->size1->setValue($details['size1']);
                    $form->size2->setValue($details['size2']);
                    $form->rent1->setValue($details['rent1']);
                    $form->rent2->setValue($details['rent2']);
                    $search1 = new Validations_Search();
                    $searchResult1 = $search1->doSearch($details);
                    $this->view->showResetButton = true;
                    $this->view->stateId = 0;
                    $this->view->stateIds = $details['state'];
                    $this->view->searchResult = $searchResult1;
                }
            }

            $this->view->stateId = 0;
            $this->view->stateIds = 0;
        }
        $this->view->form = $form;
    }

    public function detailsAction() {
        $propertyId = $this->getinputidAction();
        $db = new Ads_Model_Rentdetails();
        $details = $db->getRentDetailsBySr($propertyId);
        $this->view->details = $details;
    }

    /**
     * Get property ID.
     *   
     */
    public function getinputidAction() {
        $filters = array(
            'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
        );
        $validators = array(
            'id' => array('Int')
        );
        $input = new Zend_Filter_Input($filters, $validators);
        $input->setData($this->getRequest()->getParams());
        $id = $input->id; //property id
        return $id;
    }

    public function contactownerAction() {
        $form = new Ads_Form_Contactowner();
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $propertyId = $this->getinputidAction();
                $rentDetail = new Ads_Model_Rentdetails();
                $rentDetails = $rentDetail->getRentDetailsBySr($propertyId);
                $owner_id = $rentDetails[0]['user_id'];
                $users = new Users_Model_Users();
                $userDetails = $users->getValidUserByEmail($values['email']);
                $buyerId = 0;
                if (sizeof($userDetails) == 1) {
                    $buyerId = $userDetails[0]['id'];
                }

                $details = array(
                    'buyer_id' => $buyerId,
                    'name' => $values['name'],
                    'email' => $values['email'],
                    'contact' => $values['contact'],
                    'title' => $values['title'],
                    'message' => $values['message']
                );

                $json = json_encode(array('details' => $details));


                //save to db
                $db = new Ads_Model_Contactowner();
                $db->save(array(
                    'property_id' => $propertyId,
                    'owner_id' => $owner_id,
                    'details' => $json,
                    'date' => date('Y-m-d', date('U')),
                ));

                #send email to contect owner
                $ownerUser = $users->getUser($owner_id);
                $api = new Sendgrid_Mail();
                $emailData = array(
                    'toEmail' => $ownerUser[0]['email'],
                    'toName' => $ownerUser[0]['name'],
                    'subject' => 'Buyer interested in your property | Aparment Rental System',
                    'body' => "You are getting this email because, buyer is interested in your property. Details of interested buyer is given below.<br>Name: " . $values['name'] . "<br>Email: " . $values['email'] . '<br>Contact Number: ' . $values['contact'] . '<br>Title: ' . $values['title'] . '<br>Message: ' . $values['message'],
                );
                $api->sendMail($emailData);
                $this->_redirect('/ads/property/contactownersuccess');
            }
        }
    }

    public function contactownersuccessAction() {
        
    }

    public function resetsearchAction() {
        $userValidation = new Validations_User();
        $userId = $userValidation->getUserId();
        $userDb = new Users_Model_Users();
        $lastSearchByUserId = json_decode($userDb->getLastSearchByUserId($userId));
        $userDb->updateUser(array(
            'last_search' => null
                ), $userId);
        $this->_redirect('/search');
    }

}